#coding:utf8

'''
导出淘宝开放平台文档数据库为EXCEL格式
'''

import sys
import os

try:
	from MyPyLib import getConn
	import xlwt
except Exception as e:
	sys.exit(e)

DB_NAME='TAOBAOAPI'
TB_NAMES=['catagory','apilist','apidslist','api','apidatastruct','errorcode','faq','reqresformat']

def exportTableData(tbName):
	r_rows=list()
	db=getConn(DB_NAME)
	db.query('SELECT COUNT(1) FROM %s'%tbName)
	r=db.store_result()
	total_rows=r.fetch_row()[0][0]
	cursor=0
	limit=100
	for i in range((total_rows/limit)+1):
		db.query("SELECT * FROM %s LIMIT %d,%d"%(tbName,cursor,limit))
		r=db.store_result()
		if i==0:
			r_rows.append([desc[0] for desc in r.describe()])
		for i in range(r.num_rows()):
			r_rows.append(r.fetch_row()[0])
		cursor+=limit
	db.close()
	return r_rows

def main():
	wb=xlwt.Workbook()
	for tb_name in TB_NAMES:
		print 'sheet',tb_name
		sheet=wb.add_sheet(tb_name)
		data=exportTableData(tb_name)
		for i in range(len(data)):
			for j in range(len(data[0])):
				d=data[i][j]
				sheet.write(i,j,d)
	wb.save('doc.xls')
	pass
if __name__ == '__main__':
	main()
	pass
